//
//  UIViewSwitcher.swift
//  HFUTER
//
//  Created by HD on 15/1/17.
//  Copyright (c) 2015年 HD. All rights reserved.
//

import UIKit

class UIViewSwitcher: UIView {
    
    private var views = [UIView]()  //放置View的数组
    
    private var showItem:Int = -1   //显示的位置空就为-1

    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    func addView(view: UIView) {
        views.append(view)
        if showItem == views.count - 2 {
            showItem = views.count - 1
            showView()
        }
    }
    
    func addView(view: UIView, index: Int) {
        views.insert(view, atIndex: index)
        if showItem == views.count - 2 {
            showItem = views.count - 1
            showView()
        }
    }
    
    //显示View
    private func showView() {
        ViewUtil.removeAllViews(self)
        addSubview(views[showItem])
    }
    
    //显示指定位置的View
    func showView(index: Int) {
        if index >= views.count || views.count == 0 {
            fatalError("can not show a non-existent view")
        }
        if index < 0 {
            ViewUtil.removeAllViews(self)
            return
        }
        showItem = index
        showView()
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension UIViewSwitcher {
    var childCount: Int {
        get {
            return views.count
        }
    }
}
